import CryptoJS from 'crypto-js'

const DEFAULT_KEY = 'charset=UTF-8'

const DES_CIPHER_OPTION = {
  mode: CryptoJS.mode.ECB,
  padding: CryptoJS.pad.Pkcs7
}

/**
 * Des 加密
 * @param word
 * @param keyStr
 */
const encryptDes = (word: string, keyStr: string) => {
  keyStr = keyStr ? keyStr : DEFAULT_KEY
  let keyHex = CryptoJS.enc.Utf8.parse(keyStr)
  let encrypted = CryptoJS.DES.encrypt(word, keyHex, DES_CIPHER_OPTION)
  return encrypted.toString()
}

/**
 * Des 解密
 * @param word
 * @param keyStr
 */
const decryptDes = (word: string, keyStr: string) => {
  keyStr = keyStr ? keyStr : DEFAULT_KEY
  let keyHex = CryptoJS.enc.Utf8.parse(keyStr)
  let cipherParams = CryptoJS.lib.CipherParams.create({
    ciphertext: CryptoJS.enc.Base64.parse(word),
  });
  let decrypted = CryptoJS.DES.decrypt(cipherParams, keyHex, DES_CIPHER_OPTION)
  return CryptoJS.enc.Utf8.stringify(decrypted).toString()
}

/**
 * DES 加解密
 */
const des = {
  encrypt: (word: string, keyStr: string) => encryptDes(word, keyStr),
  decrypt: (word: string, keyStr: string) => decryptDes(word, keyStr)
}

const sha256 = (data: string) => {
  return CryptoJS.SHA256(data).toString()
}

const md5 = (data: string) => {
  return CryptoJS.MD5(data).toString()
}

export {
  des,
  md5,
  sha256
}
